package com.lc.handler;

import com.lc.type.TypeHandler;
import com.lc.type.TypeHandlerRegistry;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class ResultHandler {

    private Map<String, Class> resultMap = new HashMap<>();

    public Object getResult(String targetType, ResultSet rs) throws InstantiationException,
            IllegalAccessException, SQLException, ClassNotFoundException {

        Class targetClass = resultMap.get(targetType);
        if (targetClass == null) {
            targetClass = Class.forName(targetType);
            resultMap.put(targetType, targetClass);
        }

        Object target = targetClass.newInstance();
        Field[] fields = targetClass.getDeclaredFields();
        for (Field field : fields) {
            Object value = getRowColumnValue(field, rs);
            field.setAccessible(true);
            field.set(target, value);
        }
        return target;
    }

    private Object getRowColumnValue(Field field, ResultSet rs) throws SQLException {
        TypeHandler typeHandler = TypeHandlerRegistry.findTypeHandler(field.getType());
        Object columnValue = typeHandler.getColumnValue(rs, field.getName());
        return columnValue;
    }
}
